<template>
  <el-pagination
    v-if="total > 0"
    v-model:current-page="currentPage"
    :page-sizes="pageSizes"
    :page-size="pageSize"
    :pager-count="pagerCount"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    :hide-on-single-page="hideOnSinglePage"
    @size-change="changeSize"
    @current-change="changeCurrent"
  />
</template>
<script lang="ts" setup name="base-pagination">
import {
  ref, watch,
} from 'vue';

const props = defineProps({
  // 只有一页时是否隐藏
  hideOnSinglePage: {
    type: Boolean,
    default: false,
  },
  pageNum: {
    type: Number,
    default: 1,
  },
  defaultPageSize: {
    type: Number,
    default: 10,
  },
  pageSizes: {
    type: Array<number>,
    default: () => [10, 30, 50],
  },
  total: {
    type: Number,
    default: 0,
  },
  pagerCount: {
    type: Number,
    default: 5,
  },
});

const emits = defineEmits(['do-change', 'size-change', 'current-change']);

const currentPage = ref(1);
const pageSize = ref(10);

watch(() => props.pageNum, (newVal) => {
  currentPage.value = newVal;
}, {
  immediate: true,
});

watch(() => props.defaultPageSize, (newVal) => {
  pageSize.value = newVal;
}, {
  immediate: true,
});

function changeSize(value: number) {
  emits('size-change', value);

  currentPage.value = props.pageNum || 1;
  pageSize.value = value;
  emits('do-change', {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
  });
}

function changeCurrent(value: number) {
  emits('current-change', value);

  currentPage.value = value;
  emits('do-change', {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
  });
}
</script>
